<template>
  <el-button
    v-bind="$attrs"
    :icon="icon"
    @click="handleClick"
    :type="inTable ? '' : 'primary'"
  >
    <template v-if="status !== 'DOWNLOADING'">
      {{ text }}
    </template>
    <template v-else>
      {{ progress + '%' }}
    </template>
  </el-button>
</template>
<script>
import {
  getExportResult,
  // download,
  cancelExport,
} from '@/api/export'
const status = {
  READY: 'READY', // 可以下载
  DOWNLOADING: 'DOWNLOADING', // 下载中
  DOWNLOADED: 'DOWNLOADED', // 下载完成
  ERROR: 'ERROR', // 下载错误
}
export default {
  name: 'ExportButton',
  inheritAttrs: false,
  computed: {
    text() {
      switch (this.status) {
        case status.READY:
          return '导出'
        case status.DOWNLOADED:
          return '下载'
        case status.ERROR:
          return '重试'
        default:
          return '导出'
      }
    },
    icon() {
      return this.status === status.DOWNLOADING
        ? 'el-icon-loading'
        : this.inTable
        ? ''
        : 'el-icon-download'
    },
    href() {
      return `${process.env.VUE_APP_BASE_URL_API}/excel-export-open/download?taskId=${this.taskId}`
    },
  },
  props: {
    label: {
      type: String,
    },
    startDownload: {
      type: Function,
    },
    inTable: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    progress(val, oldval) {
      if (val === oldval) return
      if (val === 100) {
        this.status = status.DOWNLOADED
        clearInterval(this.interval)
      }
    },
  },
  destroyed() {
    if (this.status == status.DOWNLOADING) {
      this.cancel()
      this.resetStatus()
      // this.$confirm('当前导出任务取消', '导出取消', {
      //   center: true,
      //   customClass: 'tip_dialog__wrapper',
      //   showCancelButton: false,
      // }).then(() => {})
    }
  },
  data() {
    return {
      status: status.READY,
      progress: 0,
      interval: null,
      taskId: null,
    }
  },
  methods: {
    resetStatus() {
      this.status = status.READY
      this.progress = 0
      this.taskId = null

      if (this.interval) {
        clearInterval(this.interval)
        this.interval = null
      }
    },
    export() {
      this.startDownload((taskId) => {
        if (!taskId) return

        this.status = status.DOWNLOADING
        this.taskId = taskId
        this.recallSetTimeOut(taskId)
      })
    },
    recallSetTimeOut(taskId) {
      this.setInterval = setTimeout(() => {
        getExportResult({
          taskId,
        }).then((res) => {
          if (res.success) {
            this.status = status.DOWNLOADED
          } else if (res.error) {
            this.resetStatus()
            this.status = status.ERROR
            this.$message({
              type: 'warning',
              showClose: true,
              message: res.msg,
            })
          } else {
            this.progress = res.percent
            this.recallSetTimeOut(taskId)
          }
        })
      }, 300)
    },
    download() {
      if (!this.taskId) return
      let a = document.createElement('a')
      a.href = `${process.env.VUE_APP_BASE_URL_API}/excel-export-open/download?taskId=${this.taskId}`
      a.id = 'downloadFile'
      a.style.position = 'absolute'
      a.style.visibility = 'hidden'
      document.body.appendChild(a)

      a.click()
      a.remove()
      this.resetStatus()
    },
    cancel() {
      if (this.taskId) {
        cancelExport({
          taskId: this.taskId,
        })
          .then(() => {
            this.$message({
              showClose: true,
              type: 'warning',
              message: '当前导出序列已取消',
            })
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.resetStatus()
          })
      }
    },
    handleClick() {
      switch (this.status) {
        case status.READY:
          this.export()
          break
        case status.DOWNLOADING:
          this.cancel()
          break
        case status.DOWNLOADED:
          this.download()
          break
        case status.ERROR:
          this.export()
          break
      }
    },
  },
}
</script>
